package org.tamal.classinfo;

import java.io.DataInputStream;
import java.io.IOException;

/**
 * This Class represents LocalVariable of LocalVariableTable attribute.
 * @author Tamal Kanti Nath
 */
public final class LocalVariable {

    private final ClassInfo cls;
    private int start;
    private int length;
    private int nameIndex;
    private int descriptorIndex;
    private int index;

    private LocalVariable(DataInputStream in, ClassInfo cls) throws IOException
    {
        this.cls = cls;
        start = in.readUnsignedShort();
        length = in.readUnsignedShort();
        nameIndex = in.readUnsignedShort();
        descriptorIndex = in.readUnsignedShort();
        index = in.readUnsignedShort();
    }

    /**
     * Returns start_pc.
     * @return the start
     */
    public int getStart() {
        return start;
    }

    /**
     * Returns length.
     * @return the length
     */
    public int getLength() {
        return length;
    }

    /**
     * Returns name index.
     * @return the name index
     */
    public int getNameIndex() {
        return nameIndex;
    }

    /**
     * Returns name.
     * @return the name
     */
    public String getName() {
        return cls.getPool()[nameIndex].toString();
    }

    /**
     * Returns descriptor index.
     * @return the descriptor index
     */
    public int getDescriptorIndex() {
        return descriptorIndex;
    }

    /**
     * Returns descriptor.
     * @return the descriptor
     */
    public String getDescriptor() {
        return cls.getPool()[descriptorIndex].toString();
    }

    /**
     * Returns index.
     * @return the index
     */
    public int getIndex() {
        return index;
    }

    @Override
    public String toString() {
        return getName();
    }

    /**
     * Reads Local Variable Table from DataInputStream.
     * @param in the DataInputStream
     * @param cls The ClassInfo reference
     * @return the array of InnerClass
     * @throws IOException exception
     * @see Attribute
     */
    static LocalVariable[] readLocalVariableTable(DataInputStream in,
        ClassInfo cls) throws IOException {
        LocalVariable[] table = new LocalVariable[in.readUnsignedShort()];
        for (int i = 0; i < table.length; ++i) {
            table[i] = new LocalVariable(in, cls);
        }
        return table;
    }
}
